package com.todo.pro.shiro;

import java.util.HashSet;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.todo.pro.entity.SystemUser;
import com.todo.pro.service.SystemUserService;

public class JDBCRealm extends AuthorizingRealm {

	@Autowired
	private SystemUserService systemUserService;

	/***
	 * 权限验证判断
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		authorizationInfo.setRoles(new HashSet<>());
		authorizationInfo.setStringPermissions(new HashSet<>());
		return authorizationInfo;
	}

	/**
	 * 登陆检查判断
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// token中储存着输入的用户名和密码
		UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;

		Wrapper<SystemUser> systemUserWrapper = new EntityWrapper<>();
		systemUserWrapper.eq("login_name", upToken.getUsername());
		SystemUser systemUser = systemUserService.selectOne(systemUserWrapper);
		if (systemUser == null) {
			// 未知账号
			throw new UnknownAccountException();
		}

		if (systemUser.getIsEnabled() == 0) {
			// 账号禁用
			throw new DisabledAccountException();
		}
		if (systemUser.getIsLocked().intValue() == 1) {
			// 账号锁定
			throw new LockedAccountException();
		}

		String password = String.valueOf(upToken.getPassword());
		if (!systemUser.getPassword().equals(password)) {
			// 登陆密码错误
			throw new IncorrectCredentialsException();
		}
		
		// getName()
		// com.todo.pro.shiro.JDBCRealm_0
		return new SimpleAuthenticationInfo(systemUser, systemUser.getPassword(), getName());
	}

}
